package com.spring.nbrbt.tools.dateutil;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UDate {
	public static String dateToStr(Date t, String format) {
		SimpleDateFormat date_format = null;
		if ("".equals(format))
			date_format = new SimpleDateFormat("yyyy-MM-dd");
		else
			date_format = new SimpleDateFormat(format);
		return date_format.format(t);
	}

	/**
	 * 返回当前日期yyyy-mm-dd
	 */
	public static String getDate() {
		return getDate("", "", 0);
	}

	public static Date getDT() {
		return stringToDate(getDate(), "yyyy-MM-dd");
	}

	/**
	 * @模块：返回当前日期的年
	 * @作者：郑皓 @日期：2009-10-20
	 */
	public static String getYear() {
		return getDate("y", "", 0);
	}

	/**
	 * @模块：返回当前日期的月
	 * @作者：郑皓 @日期：2009-10-20
	 */
	public static String getMonth() {
		return getDate("m", "", 0);
	}

	/**
	 * @模块：返回当前日期的日
	 * @作者：郑皓 @日期：2009-10-20
	 */
	public static String getDay() {
		return getDate("d", "", 0);
	}

	/**
	 * 返回当前日期的年，月或日 type代表需要返回的数据类型：y-返回年份；m-返回月份；d-返回天；空返回yyyy-mm-dd；
	 */
	public static String getDate(String type) {
		return getDate(type, "", 0);
	}

	/**
	 * 返回带时间的当前日期
	 */
	public static String getDateTime() {
		return getDate("", "", 1);
	}

	/**
	 * 获取日期 type代表需要返回的数据类型：y-返回年份；m-返回月份；d-返回天；空返回yyyy-mm-dd；
	 * this_date代表需要处理的日期，如果为空就代表处理当前日期
	 * is_t代表是否返回有时间的日期，type必须为空，0-不返回带时间,局限于当前时间
	 */
	public static String getDate(String type, String this_date, int is_t) {

		SimpleDateFormat date_format = null;

		if (type.equals("")) {
			Date dt = new Date();
			if (is_t == 0) {
				date_format = new SimpleDateFormat("yyyy-MM-dd");
				return date_format.format(dt);
			} else {
				date_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				return date_format.format(dt);
			}

		} else {
			Date dt = null;
			if (type.equals("y"))
				date_format = new SimpleDateFormat("yyyy");
			else if (type.equals("m"))
				date_format = new SimpleDateFormat("MM");
			else if (type.equals("d"))
				date_format = new SimpleDateFormat("dd");
			else
				date_format = new SimpleDateFormat(type);

			if (this_date.equals("")) {
				dt = new Date();
				return date_format.format(dt);
			} else {
				return date_format.format(java.sql.Date.valueOf(this_date));
			}
		}
	}

	/**
	 * 功能 从日期推算前后月份,返回的类型是string,如2005-06
	 *
	 * 说明 参数ms：前一个月为-1,前两个月为-2,后一个月为1,后两个月为2,当前月为0
	 */
	public static String getMonthFromToday(Date d, int ms, String format) {
		Calendar cld = Calendar.getInstance();
		cld.setTime(d);
		cld.add(Calendar.MONTH, ms);
		Date yfdate = cld.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		String yf = sdf.format(yfdate);
		return yf;
	}

	/**
	 * 功能 从日期推算前后天,返回的类型是string,如2005-06-01
	 *
	 * 说明 参数ms：前一个天为-1,前两个天为-2,后一个天为1,后两个天为2,当前天为0
	 */
	public static String getDayFromToday(Date d, int ms, String format) {
		Calendar cld = Calendar.getInstance();
		cld.setTime(d);
		cld.add(Calendar.DAY_OF_MONTH, ms);
		Date yfdate = cld.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		String yf = sdf.format(yfdate);
		return yf;
	}

	/**
	 * 比较两个时间.
	 */
	public static final int daysBetween(Date early, Date late) {

		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(early);
		c2.setTime(late);
		return daysBetween(c1, c2);
	}

	/**
	 * 判断两个日期相差多少个月
	 */
	public static int getDiffer(Date beginDate, Date endDate) {
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(beginDate);
		c2.setTime(endDate);

		int beginYear = c1.get(Calendar.YEAR);
		int beginMonth = c1.get(Calendar.MONTH) + 1;
		int beginday = c1.get(Calendar.DAY_OF_MONTH);
		int endYear = c2.get(Calendar.YEAR);
		int endMonth = c2.get(Calendar.MONTH) + 1;
		int endday = c2.get(Calendar.DAY_OF_MONTH);

		int difMonth = (endYear - beginYear) * 12;
		difMonth = difMonth + endMonth - beginMonth;
		if ((endday - beginday) >= 0 && difMonth >= 0)
			difMonth = difMonth + 1;
		else if (difMonth < 0 && (endday - beginday) >= 0)
			difMonth = difMonth - 1;
		return difMonth;
	}

	private static final float toJulian(Calendar c) {

		int Y = c.get(Calendar.YEAR);
		int M = c.get(Calendar.MONTH);
		int D = c.get(Calendar.DATE);
		int A = Y / 100;
		int B = A / 4;
		int C = 2 - A + B;
		float E = (int) (365.25f * (Y + 4716));
		float F = (int) (30.6001f * (M + 1));
		float JD = C + D + E + F - 1524.5f;

		return JD;
	}

	private static final int daysBetween(Calendar early, Calendar late) {
		return (int) (toJulian(late) - toJulian(early));
	}

	/**
	 * 字符串转换为日期java.util.Date
	 *
	 * @param dateString
	 *            字符串
	 * @param format
	 *            日期格式
	 * @return
	 */
	public static Date stringToDate(String dateString, String format) {
		return stringToDate(dateString, format, false);
	}

	/**
	 * 字符串转换为日期java.util.Date
	 *
	 * @param dateText
	 *            字符串
	 * @param format
	 *            日期格式
	 * @param lenient
	 *            日期越界标志
	 * @return
	 */
	public static Date stringToDate(String dateText, String format, boolean lenient) {
		if (dateText == null) {
			return null;
		}
		SimpleDateFormat df = null;
		try {
			if (format == null) {
				df = new SimpleDateFormat();
			} else {
				df = new SimpleDateFormat(format);
			}
			df.setLenient(false);

			return df.parse(dateText);
		} catch (ParseException e) {

			return null;
		}
	}

	/*
	 * 判断日期格式
	 */
	public static boolean validate(String dateString) {
		// 使用正则表达式 测试 字符 符合 dddd-dd-dd 的格式(d表示数字)
		Pattern p = Pattern.compile("\\d{4}+[-]\\d{1,2}+[-]\\d{1,2}+");
		Matcher m = p.matcher(dateString);
		if (!m.matches()) {
			return false;
		}
		// 得到年月日
		String[] array = dateString.split("-");
		int year = Integer.valueOf(array[0]).intValue();
		int month = Integer.valueOf(array[1]).intValue();
		int day = Integer.valueOf(array[2]).intValue();
		if (month < 1 || month > 12)
			return false;
		int[] monthLengths = new int[] { 0, 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		if (isLeapYear(year)) {
			monthLengths[2] = 29;
		} else {
			monthLengths[2] = 28;
		}
		int monthLength = monthLengths[month];
		if (day < 1 || day > monthLength) {
			return false;
		}
		return true;
	}

	/**
	 * 获取某年某月的最后一天
	 * 
	 * @param year
	 *            年
	 * @param month
	 *            月
	 * @return 最后一天
	 */
	public static String getLastDayOfMonth(int year, int month) {
		if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
			return "31";
		}
		if (month == 4 || month == 6 || month == 9 || month == 11) {
			return "30";
		}
		if (month == 2) {
			if (isLeapYear(year)) {
				return "29";
			} else {
				return "28";
			}
		}
		return "0";
	}

	/**
	 * 获取最后一天
	 * 
	 * @return 最后一天
	 */
	public static String getLastDayOfMonth(String yd) {
		int y = Integer.parseInt(getYear());
		int m = Integer.parseInt(getMonth());
		yd = yd + "-" + getLastDayOfMonth(y, m);
		return yd;
	}

	/**
	 * 季度第一天
	 * 
	 * @return 季度第一天
	 */
	public static String getFirstDayOfQuarter(String ny) {
		String yd = "";
		int y = Integer.parseInt(ny.substring(0, 4));
		int m = Integer.parseInt(ny.substring(5, 7));
		if (m >= 1 && m <= 3)
			yd = String.valueOf(y) + "01-01";
		if (m >= 4 && m <= 6)
			yd = String.valueOf(y) + "04-01";
		if (m >= 7 && m <= 9)
			yd = String.valueOf(y) + "07-01";
		if (m >= 10 && m <= 12)
			yd = String.valueOf(y) + "10-01";
		return yd;
	}

	/**
	 * 季度最后一天
	 * 
	 * @return 季度最后一天
	 */
	public static String getLastDayOfQuarter(String ny) {
		String yd = getYear();
		int y = Integer.parseInt(ny.substring(0, 4));
		int m = Integer.parseInt(ny.substring(5, 7));
		if (m >= 1 && m <= 3)
			yd = String.valueOf(y) + "03-31";
		if (m >= 4 && m <= 6)
			yd = String.valueOf(y) + "06-30";
		if (m >= 7 && m <= 9)
			yd = String.valueOf(y) + "09-30";
		if (m >= 10 && m <= 12)
			yd = String.valueOf(y) + "12-31";
		return yd;
	}

	/** 是否是闰年 */
	private static boolean isLeapYear(int year) {
		return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
	}

	/**
	 * 相差天数
	 * 
	 * @author wojunyu
	 * @param dateFrom
	 * @param dateEnd
	 * @return
	 */
	public static String getDaysBetStr(String dateFrom, String dateEnd) {
		Date dtFrom = null;
		Date dtEnd = null;
		dtFrom = toDate(dateFrom, "yyyy-MM-dd");
		dtEnd = toDate(dateEnd, "yyyy-MM-dd");
		long begin = dtFrom.getTime();
		long end = dtEnd.getTime();
		long inter = end - begin;
		if (inter < 0) {
			inter = inter * (-1);
		}
		long dateMillSec = 24 * 60 * 60 * 1000;
		long dateCnt = inter / dateMillSec;
		long remainder = inter % dateMillSec;
		if (remainder != 0) {
			dateCnt++;
		}
		return String.valueOf(dateCnt);
	}

	/**
	 * 相差月数
	 * 
	 * @author wojunyu
	 * @param dateFrom
	 * @param dateEnd
	 * @return
	 */
	public static int getMonthBetStr(String dateFrom, String dateEnd) {
		Date dtFrom = null;
		Date dtEnd = null;
		dtFrom = toDate(dateFrom, "yyyy-MM-dd");
		dtEnd = toDate(dateEnd, "yyyy-MM-dd");
		int beginY = dtFrom.getYear();
		int endY = dtEnd.getYear();
		int beginM = dtFrom.getMonth();
		int endM = dtEnd.getMonth();
		int intY = endY - beginY;
		int intM = endM - beginM;
		int intMon = Math.abs(intY * 12 + intM);
		return intMon;
	}

	/**
	 * @author wojunyu
	 * @param sDate
	 * @param sFmt
	 * @return
	 */
	public static Date toDate(String sDate, String sFmt) {
		Date dt = null;
		try {
			dt = new SimpleDateFormat(sFmt).parse(sDate);
		} catch (ParseException e) {
			return dt;
		}
		return dt;
	}

	// 比较两个日期大小
	public static int compare_date(String DATE1, String DATE2) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date dt1 = df.parse(DATE1);
			Date dt2 = df.parse(DATE2);
			if (dt1.getTime() > dt2.getTime()) {
				System.out.println("dt1 在dt2前");
				return 1;
			} else if (dt1.getTime() < dt2.getTime()) {
				System.out.println("dt1在dt2后");
				return -1;
			} else {
				return 0;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return 0;
	}
	
	public static Date getDateByHAndM(String hm){
		Calendar cal = Calendar.getInstance();
		int day = cal.get(Calendar.DATE);       //日
		int month = cal.get(Calendar.MONTH) + 1;//当前 月
		int year = cal.get(Calendar.YEAR);      //年
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			Date date = simpleDateFormat.parse(year+"-"+month+"-"+day+" "+hm);
			return date;
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}
}
